<?php
namespace app\admin\controller;
use think\Controller;

class Category extends Base  //控制器层
{
    //构造函数 私有属性
	private $obj;
	public function _initialize(){
		$this->obj = model("Category");
		}
	
	
	public function index()
    {
        $parentId = input('get.parent_id',0,'intval');  //分类展示一or二级目录
		
		$categorys = $this->obj->getFirstCategorys($parentId);
		return $this->fetch('', ['categorys'=>$categorys,]);
	}
	
	
	
	public function add()
    {
        $categorys = $this->obj->getNormalFirstCategory();//选择一级目录后展示二级目录？？？
		
		return $this->fetch('', ['categorys'=>$categorys,] );
	}
	
	//input数据的验证和上传数据库
	public function save()
    {
       // print_r($_POST);  不太安全，主要用下面两种
	  //  print_r(input('post.'));
	 //   print_r(request()->post());
	 
	     //做下严格判定
		 if(!request()->ispost()){
			 $this->error('请求失败');
			 }
	 //把$data提交给modellayer
	     $data = input('post.');
		 $validate=validate('Category');
		 if(!$validate->scene('add')->check($data)){
			 $this->error($validate->getError());
			 
			 }
	
		if(!empty($data['id'])){
			return $this->update($data);
			}
		
		$res = $this->obj->add($data);
		if($res){
			$this->success('新增成功');
			}else{
				$this->error('新增失败');
				} 
		 
	}
	
	public function edit($id = 0){
		// echo input('get.id');
		if(intval($id < 1)){
			$this->error('参数不合法');
			}
		$category = $this->obj->get($id); // print_r($category); exit; //必须对应这个model层或者这个表的主键
		$categorys = $this->obj->getNormalFirstCategory();
		
		return $this->fetch('', [
		    'categorys'=>$categorys,
			'category'=>$category,
			] );
		
		}
	//更新数据
	public function update($data){
		$res = $this->obj->save($data,['id' => intval($data['id'])]);
		if($res){
			$this->success('更新成功');
			}else{
				$this->error('更新失败');
				}
		}
	
	//排序方法
	public function listorder($id,$listorder){
		// echo $id."<br />"; echo $listorder."<br />";
		$res = $this->obj->save(['listorder'=>$listorder],['id'=>$id]);
		if($res){
			$this->result($_SERVER['HTTP_REFERER'], 1, 'success');
			}else{
				$this->result($_SERVER['HTTP_REFERER'], 0, '更新失败');
				}
		
		
		}
	

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
?>